package org.idea.qiyu.framework.web.interceptor;

import com.alibaba.fastjson.JSON;
import org.idea.qiyu.common.context.QiyuRequestContext;
import org.idea.qiyu.common.context.QiyuCommonRequest;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.UUID;

import static org.idea.qiyu.common.constants.RequestConstants.QIYU_BASE_REQUEST;

/**
 * @Author linhao
 * @Date created in 7:32 上午 2021/9/6
 */
public class QiyuInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        QiyuCommonRequest qiyuCommonRequest = new QiyuCommonRequest();
        qiyuCommonRequest.setHeadTraceId(UUID.randomUUID().toString());
        qiyuCommonRequest.getTraceIdList().add(qiyuCommonRequest.getHeadTraceId());
        QiyuRequestContext.put(QIYU_BASE_REQUEST, qiyuCommonRequest);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        QiyuCommonRequest qiyuCommonRequest = (QiyuCommonRequest) QiyuRequestContext.get(QIYU_BASE_REQUEST);
        String json = JSON.toJSONString(qiyuCommonRequest);
        System.out.println("完整调用请求链路："+ json);
        QiyuRequestContext.put(QIYU_BASE_REQUEST,null);
    }
}
